package tcp_proxy_middleware

import (
	"fmt"
	"log"

	"github.com/youkelike/gateway/dao"
	"github.com/youkelike/gateway/reverse_proxy"
	"github.com/youkelike/gateway/tcp_server"
)

func TCPReverseProxyMiddleware() tcp_server.TcpHandlerFunc {
	return func(c *tcp_server.TcpSliceRouterContext) {
		serverInterface := c.Get("service")
		if serverInterface == nil {
			c.Conn.Write([]byte("get service empty"))
			c.Abort()
			return
		}
		serviceDetail := serverInterface.(*dao.ServiceDetail)

		addr := fmt.Sprintf(":%d", serviceDetail.TCPRule.Port)
		rb, err := dao.LoadBalancerHandler.GetLoadBalancer(serviceDetail)
		if err != nil {
			c.Conn.Write([]byte("error close"))
			log.Fatalf(" [ERROR] GetTcpLoadBalancer %v err:%v\n", addr, err)
			return
		}

		proxy := reverse_proxy.NewTcpLoadBalanceReverseProxy(c, rb)
		proxy.ServeTCP(c.Ctx, c.Conn)
		c.Abort()
	}
}
